

package com.maoshi.shop.discount.api.listener;

import com.google.common.collect.Lists;
import com.maoshi.shop.bean.app.dto.ChooseDiscountItemDto;
import com.maoshi.shop.bean.app.dto.ShopCartDto;
import com.maoshi.shop.bean.app.dto.ShopCartItemDiscountDto;
import com.maoshi.shop.bean.app.dto.ShopCartItemDto;
import com.maoshi.shop.bean.order.ShopCartEventOrder;
import com.maoshi.shop.discount.api.service.DiscountManagerService;
import com.maoshi.shop.discount.api.dto.DiscountSumDto;
import com.maoshi.shop.bean.event.ShopCartEvent;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 默认的购物车链进行组装时的操作
 * @author LGH
 */
@Component("discountShopCartListener")
@AllArgsConstructor
public class ShopCartListener {

    private DiscountManagerService discountManagerService;

    /**
     * 将店铺下的所有商品归属到该店铺的购物车当中
     */
    @EventListener(ShopCartEvent.class)
    @Order(ShopCartEventOrder.DISCOUNT)
    public void discountShopCartEvent(ShopCartEvent event) {

        ShopCartDto shopCart = event.getShopCartDto();
        List<ShopCartItemDto> shopCartItemDtoList = event.getShopCartItemDtoList();

        // 1.获取总的优惠金额
        // 2.将商品活动进行保存
        DiscountSumDto discountSumDto = discountManagerService.calculateDiscount(shopCart.getShopId(), shopCartItemDtoList);


        List<ShopCartItemDiscountDto> shopCartItemDiscountDtoList = Lists.newArrayList();

        // 对数据经行组装
        // 通过活动项id划分,获取有活动的商品项
        Map<Long, List<ShopCartItemDto>> hasDiscountShopCartItemMap = shopCartItemDtoList.stream().collect(Collectors.groupingBy(ShopCartItemDto::getDiscountId));

        for (Long discountId : hasDiscountShopCartItemMap.keySet()) {
            // 获取该列表
            List<ShopCartItemDto> shopCartItemDtos = hasDiscountShopCartItemMap.get(discountId);

            ShopCartItemDiscountDto shopCartItemDiscountDto = new ShopCartItemDiscountDto();

            ChooseDiscountItemDto chooseDiscountItemDto = discountManagerService.getChooseDiscountItemDto(discountSumDto,discountId);
            shopCartItemDiscountDto.setChooseDiscountItemDto(chooseDiscountItemDto);


            shopCartItemDiscountDto.setShopCartItems(shopCartItemDtos);
            shopCartItemDiscountDtoList.add(shopCartItemDiscountDto);
        }

        // 倒序排序，将拥有优惠活动的商品放到最上面
        Collections.reverse(shopCartItemDiscountDtoList);

        shopCart.setShopCartItemDiscounts(shopCartItemDiscountDtoList);
    }

}
